package com.bestcem.xm.om.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/9 18:42
 */
@Slf4j
@Component
public class SycExecUtil {
    private Executor omExecutor;

    @PostConstruct
    private void initExcutor() {
        try {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            //核心线程池数
            executor.setCorePoolSize(1);
            //最大线程
            executor.setMaxPoolSize(10);
            // 设置线程活跃时间（秒）
            executor.setKeepAliveSeconds(20);
            // 设置默认线程名称
            executor.setThreadNamePrefix("om-executor-");
            // 等待所有任务结束后再关闭线程池
            executor.setWaitForTasksToCompleteOnShutdown(true);
            // 设置队列容量
            executor.setQueueCapacity(0);
            //队列满，线程被拒绝执行策略
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            this.omExecutor = executor;
        } catch (NoSuchBeanDefinitionException e) {
            if (log.isInfoEnabled()) {
                log.info("[OM] 异步发送邮件功能未开启");
            }
        }
    }

    public void asycnExec(Runnable command) {
        if (omExecutor != null) {
            omExecutor.execute(command);
        } else {
            if (log.isInfoEnabled()) {
                log.info("[OM] 异步发送邮件功能未开启");
            }
        }
    }
}
